package cn.com.demo.tp01.filter.Factory;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
@Component
public class myGatewayFilterGatewayFilterFactory  extends AbstractGatewayFilterFactory<myGatewayFilterGatewayFilterFactory .myConfig> {
    public myGatewayFilterGatewayFilterFactory (){
        super(myConfig.class);
    }

    @Override
    public GatewayFilter apply(myConfig config) {
        return ((exchange, chain) -> {
            Mono<Void> mono = null;
            String name=config.getParam1();
            String value=config.getParam2();
            int age1=Integer.parseInt(value);

            ServerHttpRequest request = exchange.getRequest();
            MultiValueMap<String, String> queryParams = request.getQueryParams();
            String age = queryParams.getFirst(name);// 请求传入的age
            int age2 = Integer.parseInt(age);
            // 比较age和value，是否age>value
            if(age2>age1) {
                // 如果大于， 继续后面走
                return chain.filter(exchange);
            }else {
                // 否则，拦截，输出未成年
                byte[] bytes = "未成年年不能访问".getBytes();
                ServerHttpResponse response = exchange.getResponse();
                HttpHeaders headers = response.getHeaders();
                headers.setContentType(MediaType.TEXT_HTML);
                headers.set("Content-Type", "text/html;charset=utf-8");
                DataBuffer wrap = response.bufferFactory().wrap(bytes);
                return response.writeWith(Mono.just(wrap));
            }


        });
    }
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("param1", "param2");
    }

    static class  myConfig{
        private  String param1;
        private  String param2;

        public String getParam1() {
            return param1;
        }

        public void setParam1(String param1) {
            this.param1 = param1;
        }

        public String getParam2() {
            return param2;
        }

        public void setParam2(String param2) {
            this.param2 = param2;
        }
    }
}

